﻿using System;
using System.Linq;
using ATTools.Models;
using ATTools.Services;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Handlers;
using Orchard.Core.Common.Models;
using Orchard.Data;
using Orchard.Environment.Extensions;
using Orchard.Media.Services;
using Orchard.Settings;
using Orchard.Utility.Extensions;

namespace ATTools.Handlers
{
    [OrchardFeature("ATTools")]
    public class SoundHandler : ContentHandler
    {

        public SoundHandler(IRepository<SoundRecord> repository, IMediaService mediaService, ISiteService siteService, ISpeakService speakService, ITranslationService translationService)
        {
            Filters.Add(StorageFilter.For(repository));
            //Generate the sound file based on the bodytext when the content item is publishing
            OnPublishing<BodyPart>((context, bodyPart) =>
                {
                    var soundpart = context.ContentItem.As<SoundPart>();

                    if (soundpart != null)
                    {
                        string mediaFolder = "ATTools-Soundfiles";
                        string fileName = context.PublishingItemVersionRecord.Id + ".wav";

                        if (context.PreviousItemVersionRecord != null)
                        {
                            string previousFileName = context.PreviousItemVersionRecord.Id + ".wav";
                            try
                            {
                                mediaService.DeleteFile(mediaFolder, previousFileName);
                            }
                            catch (Exception)
                            {
                                ;
                            }

                        }

                        var speakSettings = siteService.GetSiteSettings().As<ATToolsSettingsPart>().Record;

                        string text = bodyPart.Text.RemoveTags();

                        string language = soundpart.Record.LanguageOfSound;
                        if (language == null || language == "Auto detect")
                        {
                            string[] texts = new string[1] { text };
                            language = translationService.DetectLanguages(texts).ElementAt(0);

                        }

                        string url = speakService.SaveTextAsSoundFile(text, language, mediaFolder, fileName);

                        // Set the model with the url
                        soundpart.SoundString = url;

                    }

                });

        }

    }
}